package com.jaynux.app;
import android.app.*;
import android.content.*;
import android.database.sqlite.*;
import android.os.*;
import android.os.PowerManager.*;
import android.util.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;

import com.jaynux.app.RandomRun.*;
import com.jaynux.app.provider.*;

public class main extends Activity {
	
	private ImgThread mImgThread;
    /** A handle to the View in which the game is running. */
    private RandomRun mRandomRun;

    // the play start button
    private Button mButton;

    // used to hit retry
    private Button mButtonRetry;

    // used to go main
    private Button mButtonMain;
    
    // the window for instructions and such
    private TextView mTextView;

    // game window meter
    private TextView mMeterView;
    // game window timer
    private TextView mTimerView;
    
    //DB관련
	private SQLiteDatabase mDb;	// SQLite DB에 접근하기위한 변수
	private SaveDatabases mSaveDatabases;
	
	private PowerManager mPm;	//전원 관리
	private WakeLock mWakeLock;
	
    /** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.randomrun);
        
        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        // get handles to the RandomRunView from XML and the RandomRun thread.
        mRandomRun = (RandomRun)findViewById(R.id.randomRun);
        
        //thread를 얻어온다. 이렇게해서 런처에서 Thrad를 통제 할 수 있게 된다.
        mImgThread = mRandomRun.getThread();
        
        // look up the happy shiny button
        mButton = (Button)findViewById(R.id.Button01);
        // 본인 스스로를 리스너로 만든다.
        mButton.setOnClickListener(pOnClickListener);
        
        //본인 스스로를 리스너로 만든다.
        mButtonRetry = (Button)findViewById(R.id.Button02);
        mButtonRetry.setOnClickListener(pOnClickListener);

        mButtonMain = (Button)findViewById(R.id.Button03);
        mButtonMain.setOnClickListener(pOnClickListener);
        
        // set up handles for instruction text and game timer text
        mTextView = (TextView)findViewById(R.id.text);//정보 표시 텍스트
        mMeterView = (TextView)findViewById(R.id.meter); // 거리 표시 텍스트
        mTimerView = (TextView)findViewById(R.id.timer); // 시간 표시 텍스트
        
        //아래에 거리를 표시하기위해 TextView를 인자로 넘겨준다.
        mRandomRun.setMeterView(mMeterView);
        //위에 시간을 표시하기 위해 TextView를 인자로 넘겨준다.
        mRandomRun.setTimerView(mTimerView);
        
        //버튼도 끝나고 실해해주기 위해 인자로 넘겨 준다.
        mRandomRun.SetButtonView(mButtonRetry);
        //버튼도 끝나고 실해해주기 위해 인자로 넘겨 준다.
        mRandomRun.SetButtonMain(mButtonMain);
        //정보를 표시하기위해 인자로 넘겨준다.
        mRandomRun.SetTextView(mTextView);
        //setting 값을 전달
        mImgThread.setSettingValue(b);
        
        //DB를 오픈한다.
		mSaveDatabases = new SaveDatabases(this) ;
		mDb = mSaveDatabases.getWritableDatabase();
		mRandomRun.setSQLiteDB(mDb);
		
		// WakeLock 객체 생성
		mPm = (PowerManager)getSystemService(Context.POWER_SERVICE);
		mWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "tag");
    }
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//화면 꺼짐을 방지를 풀어준다.
		if (mWakeLock.isHeld()) {
			mWakeLock.release();
		}
		if(mImgThread.mState != mImgThread.STATE_LOSE && mImgThread.mState != mImgThread.STATE_PLAY) {
			mImgThread.setGameState(mImgThread.STATE_PAUSE);
			mTextView.setVisibility(View.VISIBLE);
			mButtonRetry.setVisibility(View.VISIBLE);
			mButtonMain.setVisibility(View.VISIBLE);
			mMeterView.setVisibility(View.INVISIBLE);
		    mTimerView.setVisibility(View.INVISIBLE);
			mTextView.setText("Paused");
			mButtonRetry.setText("RESTART");
		}
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mWakeLock.acquire();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//DB를 쓰고난 다음에 닫아 주어야 한다.
		mDb.close();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onPause();
			return true;
		} else 
			return false;
	}

	OnClickListener pOnClickListener = new OnClickListener() {
		public void onClick(View v) {
			// TODO Auto-generated method stub
	        // we have entered game play, now we about to start running
	        if(mButtonMain.equals(v)) {
	        	Intent i = new Intent(main.this, RaceStartActivity.class);
	        	startActivity(i);
	        	finish();
	        }
			
			if (mButton.equals(v)) {
	            mButton.setVisibility(View.INVISIBLE);
	            mTextView.setVisibility(View.INVISIBLE);
	            mMeterView.setVisibility(View.VISIBLE);
	            mTimerView.setVisibility(View.VISIBLE);
	            mButtonMain.setVisibility(View.INVISIBLE);
	            mImgThread.setGameState(ImgThread.STATE_RUNNING);

	        }
	        
	        if(mImgThread.getGameState() == ImgThread.STATE_PAUSE && mButtonRetry.equals(v)) {
	        	mImgThread.DoResume();
	        	mTextView.setVisibility(View.INVISIBLE);
				mButtonRetry.setVisibility(View.INVISIBLE);
				mButtonMain.setVisibility(View.INVISIBLE);
				mMeterView.setVisibility(View.VISIBLE);
			    mTimerView.setVisibility(View.VISIBLE);
				mButtonRetry.setText("RETRY");
	        }
	        
	        // this is a retry button
	        else if (mButtonRetry.equals(v)) {

	            mTextView.setText(R.string.helpText);

	            mButton.setText("PLAY!");
	            mButtonRetry.setVisibility(View.INVISIBLE);
	            mButtonMain.setVisibility(View.VISIBLE);
	            // mButtonRestart.setVisibility(View.INVISIBLE);

	            mTextView.setVisibility(View.VISIBLE);
	            mButton.setText("PLAY!");
	            mButton.setVisibility(View.VISIBLE);

	            mImgThread.setGameState(ImgThread.STATE_PLAY);

	        } else {
	            Log.d("JB VIEW", "unknown click " + v.getId());
	            Log.d("JB VIEW", "state is  " + mImgThread.mState);
	        }
		}
	};
}